import qs from 'qs'
import axios from 'axios'
import store from '../store'
import router from '../router'

const paramsSerializer = params => qs.stringify(params)

//拦截器
function Interceptors(instance) {
  // 请求拦截器
  instance.interceptors.request.use(
    config => {
      if (store.state?.accessToken)
        Object.assign(config.headers, {
          Authorization: 'Bearer ' + store.state.accessToken,
        })
      return config
    },
    error => {
      console.error(error.config)
      return Promise.reject('请求异常')
    }
  )
  // 响应拦截器
  instance.interceptors.response.use(
    resp => {
      const d = resp.data
      if (d.code === 0) return d.data ?? d.message
      return Promise.reject(d.data ?? d.message)
    },
    error => {
      if (error?.response) {
        const resp = error.response
        if (resp.status == 401) {
          store.commit('REMOVE_ALL')
          router.push({ name: 'Login' })
          return Promise.reject('请登录')
        }
        else if (resp.status >= 400 && resp.status < 500) {
          router.push('/404')
          return Promise.reject('接口不存在')
        } else if (resp.status >= 500) {
          router.push('/500')
          return Promise.reject('服务器错误')
        } else {
          return Promise.reject('未处理的响应异常')
        }
      } else if (error?.request) {
        return Promise.reject(error.request)
      } else return Promise.reject(error?.message)
    }
  )
}

//导出默认axios
export default axios

//凭证请求
export function request() {
  const instance = axios.create({ paramsSerializer })
  Interceptors(instance) // 添加拦截器
  return instance
}
